import axios from "axios";
import store from "@/store/index"
import router from "@/router";
import { Indicator } from 'mint-ui';

export function api1(config) {
  return new Promise((resolve, reject) => {
    //请求前
    config.headers = config.headers || {}

    Indicator.open('加载中...');

    const instance = axios.create({
      baseURL: 'http://localhost:3000',
      timeout: 5000
    })
    //发生真正的网络请求
    instance(config).then(res => {
      let data = res.data.data;

      //请求完成
      setTimeout(() =>{
        Indicator.close();
      },500)

      resolve(data)
    }).catch(err => {
      reject(err)
    })

    //对请求前的拦截器
    instance.interceptors.request.use(
      config => {
        // config.headers['Authorization'] = utilsAuth.getShopToken();
        // return config
        
        //判断是否传入headers:{token:true},那么则判断用户是否是登录状态
        if(config.headers.token){
          config.headers.token = store.state.user.token
          if(!config.headers.token){
            setTimeout(() =>{
              Indicator.close();
            },500)
            router.push('/login')
            return
          }
        }
      },
      error => {
        return Promise.reject(error)
      }
    )

    //对响应的拦截器
    instance.interceptors.response.use(res => {
      //TODO 隐藏加载框
      //checkLoading(2);
      // token失败 或 签名失败
      if (res.data.status === 'fail') {
        switch (res.data.code) {
          case '502':
          case '503':
            // TODO 登陆、请求失败等相关信息，然后跳转到登录页面
            // router.replace({name: 'signin'})
            router.replace('/login')
            break;
        }
      }

      return res
    }, error => {
      //TODO 隐藏加载框
      //checkLoading(2);

      if (error && error.response && error.response.status) {
        switch (error.response.status) {
          case 400:
            error.msg = '错误请求'
            break;
          case 401:
            error.msg = '未授权，请重新登录'
            break;
          case 403:
            error.msg = '拒绝访问'
            break;
          case 404:
            error.msg = '请求错误,未找到该资源'
            break;
          case 405:
            error.msg = '请求方法未允许'
            break;
          case 408:
            error.msg = '请求超时'
            break;
          case 500:
            error.msg = '服务器端出错'
            break;
          case 501:
            error.msg = '网络未实现'
            break;
          case 502:
            error.msg = '网络错误'
            break;
          case 503:
            error.msg = '服务不可用'
            break;
          case 504:
            error.msg = '网络超时'
            break;
          case 505:
            error.msg = 'http版本不支持该请求'
            break;
          default:
            error.msg = `连接错误 ${error.response.status}`
        }
      } else {
        error.msg = '连接错误'
      }
      if (error.data) {
        error.data.status = 'fail'
        error.data.msg = error.msg
      }

      return Promise.reject(error)
    })

  })







}